package com.xy.p2p.action.front;



import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.mapping.Array;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.web.CookieUtils;
import com.xy.common.web.RequestUtils;
import com.xy.core.util.DateUtil;
import com.xy.core.web.WebErrors;

import com.xy.p2p.dao.impl.TfileaveamessageDaoImpl;
import com.xy.p2p.model.Tfileaveamessage;
import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Ttenderrecord;
import com.xy.p2p.service.TfileaveamessageService;
import com.xy.p2p.service.TfinanceinfoService;
import com.xy.p2p.service.TmemberassetaccountService;
import com.xy.p2p.service.TtenderrecordService;



@Controller
public class TfinanceinfoAction{
	private static final Logger log = LoggerFactory.getLogger(TfinanceinfoAction.class);
	public TfinanceinfoAction() {
	}
	private final int PAGESIZE = 20;
	
	//跳转到填写融资申请页面
	@RequestMapping("/member/v_tfinanceinfoInfo.jspx")
	public String info(Long fiid , Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		if(null!=fiid){
			model.addAttribute("tfinanceinfo", tfinanceinfoService.get(fiid));
		}else{
			model.addAttribute("tfinanceinfo", new Tfinanceinfo());
		}
		if(tfinanceinfoService.checkNull(tmember))
			return "redirect:/member/toMemberinfoEdit.jspx";
		setDict(model);
		return "/front/businessPage/financeInfo.html";
	}
	//融资申请提交
	@RequestMapping("/member/o_tfinanceinfoSubmit.jspx")
	public String submit(Tfinanceinfo tfinanceinfo, Integer pageNo,
			HttpServletRequest request, ModelMap model,String date) {
		Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		if(tfinanceinfo.getFinanceamount()%50!=0){
			model.addAttribute("ErrorMsg", "融资金额必须是50的倍数. ");
			return "forward:/member/v_tfinanceinfoDetail.jspx";
		}
		if("m".equals(date)){
			tfinanceinfo.setFinanceallotedtime(tfinanceinfo.getFinanceallotedtime()*30);
		}
		if(null == tfinanceinfo.getRepaymentmod())
			tfinanceinfo.setRepaymentmod(1);
		if(null == tfinanceinfo.getRepaymentperiod())
			tfinanceinfo.setRepaymentperiod(1);
		tfinanceinfo.setApplicationdate(new Date());
//		if(null == request.getParameter("draft"))
//			tfinanceinfo.setStatus(0);
//		else
//			tfinanceinfo.setStatus(12);
		tfinanceinfo.setFinancepa(tfinanceinfo.getFinancepa()/100.00);
		tfinanceinfo.setTmember(tmember);
		tfinanceinfo.setFinancelimit(DateUtil.addDate(new Date(), 7));
		tfinanceinfo.setTargettype(1);
		try {
			tfinanceinfoService.save(tfinanceinfo);
			return "redirect:/member/v_tfinanceinfoList.jspx";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
	//查询未到限期和未投满的标的列表(用于投资者查看可投标列表)
	@RequestMapping("/member/v_tfinanceinfoList1.jspx")
	public String listForTender(Integer pageNo,Tfinanceinfo tfinanceinfo, HttpServletRequest request, ModelMap model,String[] targetType,String[] dateList,String[] credit) {
 		if (pageNo == null)
			pageNo = 1;
		//增加条件筛选功能
		List<Map<String,Integer>> qdate = new ArrayList<Map<String,Integer>>();
		//筛选, 如果条件中有不限条件的就清空条件
		if(null == targetType){
			targetType = new String[]{};
		}
		if(null == credit){
			credit = new String[]{};
		}
		if(null == dateList){
			dateList = new String[]{};
		}
		for(String s : targetType){
			if(s.trim().equals("")){
				targetType = new String[]{};
			}
		}
		for (String s : credit) {
			if(s.trim().equals("")){
				credit = new String[]{};
			}
		}
		//解析日期
		try {
			for (String s : dateList) {
				String[] ts = s.split(",");
				if(ts.length<2){
					continue;
				}
				Map<String,Integer> m = new HashMap<String, Integer>();
				m.put("begin", Integer.valueOf(ts[0]));
				m.put("end", Integer.valueOf(ts[1]));
				qdate.add(m);
			}
		} catch (Exception e) {
			log.debug("++++++++++++投标列表筛选日期参数错误++++++++++++");
		}
//		List<Tfinanceinfo> list = tfinanceinfoService.getEnableFinanceByCondition(targetType, qdate, credit);
		Pagination pagination = tfinanceinfoService.getEnableFinanceByCondition(targetType, qdate, credit,pageNo,PAGESIZE);
		//end
//		int pageSize = 10;
//		Pagination pagination =new Pagination(pageNo, pageSize, list.size());
//		if(pageNo*pageSize>list.size()){
//			pagination.setList(list.subList((pageNo-1)*pageSize , list.size()));
//		}else{
//			pagination.setList(list.subList((pageNo-1)*pageSize , (pageNo*pageSize)));
//		}
		for(Tfinanceinfo t : (List<Tfinanceinfo>)pagination.getList()){
			tfinanceinfoService.putTenderMoneyIntoEntity(t);
		}
		model.addAttribute("pagination", pagination);
		model.addAttribute("targetType", targetType);
		model.addAttribute("dateList", dateList);
		model.addAttribute("credit", credit);
//		model.addAttribute("list", list);   
        setDict(model);
		return "/front/businessPage/tenderList.html";
	}
	
	
	//融资标的信息表详情
	@RequestMapping("/member/v_tfinanceinfoDetail.jspx")
	public String detail(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		tfinanceinfo = tfinanceinfoService.putTenderMoneyIntoEntity(tfinanceinfo);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
		// other
		Map<String, Object> map = new HashMap<String, Object>();
		Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		map.put("Tmember", tmember);
		Tmemberassetaccount account = tmemberassetaccountService.getTmemberassetaccount(map).get(0);
		model.addAttribute("accont", account);
		model.addAttribute("financeinfo", tfinanceinfoService.getFinanceHelper(tfinanceinfo.getTmember()));
		//排序
		map.clear();
		map.put("Tfinanceinfo", tfinanceinfo);
		List<Tfileaveamessage> msgList = tfileaveamessageService.getTfileaveamessage(map);
		Collections.sort(msgList);
		model.addAttribute("msgList", msgList);
		setDict(model);
		if (8 == tfinanceinfo.getTargettype())
			return "/front/businessPage/balanceDetail.html";
		else
			return "/front/businessPage/financeDetail.html";
	}
	
	//查看标的详细, 不能进行购买操作
	@RequestMapping("/member/v_tfinanceinfoDetail2.jspx")
	public String detail2(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		tfinanceinfo = tfinanceinfoService.putTenderMoneyIntoEntity(tfinanceinfo);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
		setDict(model);
		Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		model.addAttribute("operation", "readonly");
		model.addAttribute("financeinfo", tfinanceinfoService.getFinanceHelper(tfinanceinfo.getTmember()));
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("Tmember", tmember);
		Tmemberassetaccount account = tmemberassetaccountService.getTmemberassetaccount(map2).get(0);
		model.addAttribute("accont", account);
		//排序
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Tfinanceinfo", tfinanceinfo);
		List<Tfileaveamessage> msgList = tfileaveamessageService.getTfileaveamessage(map);
		Collections.sort(msgList);
		model.addAttribute("msgList", msgList);
		if (8 == tfinanceinfo.getTargettype())
			return "/front/businessPage/balanceDetail.html";
		else
			return "/front/businessPage/financeDetail.html";
	}

	//个人中心里面的融资信息
	@RequestMapping("/member/v_tfinanceinfoList.jspx")
	public String listPage(Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = new Tfinanceinfo();
		tfinanceinfo.setTmember((Tmember)request.getSession().getAttribute(TmemberAction.AUTH_KEY));
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tfinanceinfoService.getTfinanceinfoByPage(toMap(tfinanceinfo),
				pageNo, CookieUtils.getPageSize(request));
		//获取余额贷的下一还款总金额
		Map<String, Object> queryMap = new HashMap<String, Object>();
		for(Tfinanceinfo t : (List<Tfinanceinfo>)pagination.getList()){
			if(t.getTargettype()!=8)
				continue;
			queryMap.put("Tfinanceinfo", t);
			double temp = 0;
			for(Ttenderrecord td : ttenderrecordService.getTtenderrecord(queryMap)){
				temp+= td.getMibmoney()*td.getFinancepa()/365;
			}
			//临时存放该余额贷标的的下期待交费用
			t.setAlino(temp);
		}
//		List<Tfinanceinfo> list = tfinanceinfoService.getTfinanceinfo(toMap(tfinanceinfo));
		model.addAttribute("pagination", pagination);
        setDict(model);
        //用于导航栏
        model.addAttribute("dis", 12);
		return "/front/member/financeList.html";
	}

	//余额贷列表
	@RequestMapping("/member/v_tfinanceinfoYEDList.jspx")
	public String YEDList(Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		model.addAttribute("list", tfinanceinfoService.getYED());
        setDict(model);
		return "/front/businessPage/balanceList.html";
	}
	
	/**
	 * 融资标的信息表删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/member/o_tfinanceinfoDelete.jspx")
	public String delete(long[] ids) {
		if (ids != null) {
			for (long id : ids) {
				tfinanceinfoService.remove(id);
			}
		}
		return "redirect:/member/v_tfinanceinfoList.jspx";
	}
 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tfinanceinfo
	 * @return
	 */	private Map<String,Object> toMap(Tfinanceinfo tfinanceinfo){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(tfinanceinfo.getFiid()!=null&&!tfinanceinfo.getFiid().equals("")){
			map.put("fiid", tfinanceinfo.getFiid());
		}
		if(tfinanceinfo.getTmember()!=null){
			map.put("Tmember", tfinanceinfo.getTmember());
		}
		if(tfinanceinfo.getFinancekey()!=null&&!tfinanceinfo.getFinancekey().equals("")){
			map.put("financekey", tfinanceinfo.getFinancekey());
		}
		if(tfinanceinfo.getFinanceuse()!=null&&!tfinanceinfo.getFinanceuse().equals("")){
			map.put("financeuse", tfinanceinfo.getFinanceuse());
		}
		if(tfinanceinfo.getFinanceamount()!=null&&!tfinanceinfo.getFinanceamount().equals("")){
			map.put("financeamount", tfinanceinfo.getFinanceamount());
		}
		if(tfinanceinfo.getFinanceallotedtime()!=null&&!tfinanceinfo.getFinanceallotedtime().equals("")){
			map.put("financeallotedtime", tfinanceinfo.getFinanceallotedtime());
		}
		if(tfinanceinfo.getFinancepa()!=null&&!tfinanceinfo.getFinancepa().equals("")){
			map.put("financepa", tfinanceinfo.getFinancepa());
		}
		if(tfinanceinfo.getRepaymentperiod()!=null&&!tfinanceinfo.getRepaymentperiod().equals("")){
			map.put("repaymentperiod", tfinanceinfo.getRepaymentperiod());
		}
		if(tfinanceinfo.getRepaymentmod()!=null&&!tfinanceinfo.getRepaymentmod().equals("")){
			map.put("repaymentmod", tfinanceinfo.getRepaymentmod());
		}
		if(tfinanceinfo.getFinancelimit()!=null&&!tfinanceinfo.getFinancelimit().equals("")){
			map.put("financelimit", tfinanceinfo.getFinancelimit());
		}
		if(tfinanceinfo.getFinancedescription()!=null&&!tfinanceinfo.getFinancedescription().equals("")){
			map.put("financedescription", tfinanceinfo.getFinancedescription());
		}
		if(tfinanceinfo.getStatus()!=null&&!tfinanceinfo.getStatus().equals("")){
			map.put("status", tfinanceinfo.getStatus());
		}
		if(tfinanceinfo.getItfdate()!=null&&!tfinanceinfo.getItfdate().equals("")){
			map.put("itfdate", tfinanceinfo.getItfdate());
		}
		if(tfinanceinfo.getNrdate()!=null&&!tfinanceinfo.getNrdate().equals("")){
			map.put("nrdate", tfinanceinfo.getNrdate());
		}
		if(tfinanceinfo.getPlsf()!=null&&!tfinanceinfo.getPlsf().equals("")){
			map.put("plsf", tfinanceinfo.getPlsf());
		}
		if(tfinanceinfo.getMfrl()!=null&&!tfinanceinfo.getMfrl().equals("")){
			map.put("mfrl", tfinanceinfo.getMfrl());
		}
		if(tfinanceinfo.getSubpri()!=null&&!tfinanceinfo.getSubpri().equals("")){
			map.put("subpri", tfinanceinfo.getSubpri());
		}
		if(tfinanceinfo.getAlino()!=null&&!tfinanceinfo.getAlino().equals("")){
			map.put("alino", tfinanceinfo.getAlino());
		}
		if(tfinanceinfo.getMftba()!=null&&!tfinanceinfo.getMftba().equals("")){
			map.put("mftba", tfinanceinfo.getMftba());
		}      
		if(tfinanceinfo.getTargettype()!=null&&!tfinanceinfo.getTargettype().equals("")){
			map.put("targettype", tfinanceinfo.getTargettype());
		}
		if(tfinanceinfo.getRemark()!=null&&!tfinanceinfo.getRemark().equals("")){
			map.put("remark", tfinanceinfo.getRemark());
		}
		if(tfinanceinfo.getApplicationdate()!=null&&!tfinanceinfo.getApplicationdate().equals("")){
			map.put("applicationdate", tfinanceinfo.getApplicationdate());
		}  
		if(tfinanceinfo.getRewardrate()!=null&&!tfinanceinfo.getRewardrate().equals("")){
			map.put("rewardrate", tfinanceinfo.getRewardrate());
		} 
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
      model.addAttribute("repaymentperiodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTPERIOD));
      model.addAttribute("repaymentmodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTMOD));
      model.addAttribute("fstatusMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_STATUS));		
      model.addAttribute("targettypeMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_TARGETTYPE));
      model.addAttribute("supportmethodsMap", DictUtils.getDictByType(DictUtils.SUPPORT_METHODS));	
     //用户map
      model.addAttribute("usertypeMap", DictUtils.getDictByType(DictUtils.TMEMBER_USERTYPE));
      model.addAttribute("sexMap", DictUtils.getDictByType(DictUtils.TMEMBER_SEX));
      model.addAttribute("edudegreeMap", DictUtils.getDictByType(DictUtils.TMEMBER_EDUDEGREE));
      model.addAttribute("marriageMap", DictUtils.getDictByType(DictUtils.TMEMBER_MARRIAGE));
      model.addAttribute("worktypeMap", DictUtils.getDictByType(DictUtils.TMEMBER_WORKTYPE));
      model.addAttribute("corpsizeMap", DictUtils.getDictByType(DictUtils.TMEMBER_CORPSIZE));
      model.addAttribute("statusMap", DictUtils.getDictByType(DictUtils.TMEMBER_STATUS));
      model.addAttribute("cbcreditMap", DictUtils.getDictByType(DictUtils.TMEMBER_CBCREDIT));
      model.addAttribute("fixedassetsMap", DictUtils.getDictByType(DictUtils.TMEMBER_FIXEDASSETS));
      model.addAttribute("currentassetsMap", DictUtils.getDictByType(DictUtils.TMEMBER_CURRENTASSETS));	
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Tfinanceinfo tfinanceinfo, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}

   
      
	@Resource
	private TfinanceinfoService tfinanceinfoService;   
	@Resource
	private TmemberassetaccountService tmemberassetaccountService;
	@Resource
	private TtenderrecordService ttenderrecordService; 
	@Resource
	private TfileaveamessageService tfileaveamessageService;
}